<!-- 规则配置 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" size="720px" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">{{ handleType == 'info' ? '查看' : '配置' }}</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<template v-if="curNodeList.length > 0">
						<div v-for="(item, index) in curNodeList" :key="index" :class="index > 0 && 'zs-space-top-bg'">
							<div class="zs-align-center zs-space-bottom" :id="`sm-drawer-demo-card-${index + 1}`">
								<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
								<div class="zs-title">计费规则{{ index + 1 }}</div>
							</div>
							<div class="zs-card zs-space-bottom">
								<el-table class="zs-table-page-main" :data="item.list">
									<el-table-column type="index" label="序号" width="60" align="center" />
									<el-table-column prop="name" label="名称" align="left" />
									<el-table-column label="开始时间" align="right">
										<template #default="scope">
											<el-time-picker v-model="scope.row.startTime" style="width: 100%" :placeholder="scope.$index > 0 ? '-' : ''" value-format="HH:mm" format="HH:mm" disabled @change="timeChange($event, scope.row, 'endTime')" />
											<!-- <el-time-select start="00:00" step="00:15" end="23:59" v-model="scope.row.startTime" style="width: 100%" :disabled="true" :placeholder="scope.$index > 0 ? '-' : ''" @change="timeChange($event, scope.row, 'endTime')" /> -->
											<!-- <el-time-select start="00:00" step="00:15" end="23:59" v-model="scope.row.startTime" style="width: 100%" :disabled="scope.$index > 0 || isReadOnly ? true : false" :placeholder="scope.$index > 0 ? '-' : ''" @change="timeChange($event, scope.row, 'endTime')" /> -->
										</template>
									</el-table-column>
									<el-table-column label="结束时间" align="right">
										<template #default="scope">
											<el-time-picker v-model="scope.row.endTime" style="width: 100%" :placeholder="scope.$index > 0 ? '-' : ''" value-format="HH:mm" format="HH:mm" disabled @change="timeChange($event, scope.row, 'startTime')" />
											<!-- <el-time-select start="00:00" step="00:15" end="23:59" v-model="scope.row.endTime" style="width: 100%" :disabled="true" :placeholder="scope.$index > 0 ? '-' : ''" @change="timeChange($event, scope.row, 'startTime')" /> -->
											<!-- <el-time-select start="00:00" step="00:15" end="23:59" v-model="scope.row.endTime" style="width: 100%" :disabled="scope.$index > 0 || isReadOnly ? true : false" :placeholder="scope.$index > 0 ? '-' : ''" @change="timeChange($event, scope.row, 'startTime')" /> -->
										</template>
									</el-table-column>
									<el-table-column label="单价" align="right">
										<template #default="scope">
											<el-input v-model="scope.row.price" maxlength="8" style="width: 100%" :disabled="scope.$index > 0 || isReadOnly ? true : false" :placeholder="scope.$index > 0 ? '-' : ''" @blur="judgePrice(scope.row)" />
										</template>
									</el-table-column>
								</el-table>
							</div>
							<div class="zs-card zs-space-bottom">
								<HsForm :filed-list="item.formList" ref="formRef" :isDisabled="isReadOnly" @selectChange="selectChange"></HsForm>
							</div>
						</div>
					</template>
					<el-empty v-else description="暂无数据" />
					<el-button v-if="handleType == 'edit'" class="add-btn zs-link" plain @click="addItem">新增</el-button>
				</el-scrollbar>
				<DocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import HsForm from '@/components/hsForm.vue';
	import DocWrapper from '@/components/DocWrapper.vue';
	import { chargeRules } from '@/config/form/energy.js';
	import { chargeWaterInfoApi, chargeWaterSaveApi, chargeEleInfoApi, chargeEleSaveApi } from '@/api/energy.js';
	import { ElMessage } from 'element-plus';
	import { ref, watch, nextTick } from 'vue';
	import { deepClone } from '@/utils/publicUtils';
	import { judgeDIffTime } from '@/utils/formRules';

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		energyType: { type: String, default: '' },
		currentRow: { type: Object },
	});
	const emit = defineEmits(['close']);
	let formRef = ref([]);
	let isShowDrawer = ref(props.isShow);
	let curNodeList = ref([]);

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			newVal && getInfo();
		},
	);

	//初始化信息
	const getInfo = async () => {
		curNodeList.value = [];
		let res = props.energyType == 'water' ? await chargeWaterInfoApi(props.currentRow.projectCode) : await chargeEleInfoApi(props.currentRow.projectCode);
		if (res.data.data && res.data.data.length > 0) {
			res.data.data.forEach((item, index) => {
				let sub = index + 1;
				let formList = initFormList(item);
				let timeObj = {
					name: '计费规则' + sub,
					id: 'sm-drawer-demo-card-' + sub,
					list: [
						{ name: '平值设置', startTime: item.averageStartTime, endTime: item.averageEndTime, price: item.averageUnitPrice },
						{ name: '峰值设置', startTime: item.peakValueStartTime, endTime: item.peakValueEndTime, price: item.peakValueUnitPrice },
						{ name: '谷值设置', startTime: item.valleyValueStartTime, endTime: item.valleyValueEndTime, price: item.valleyValueUnitPrice },
					],
					formList: formList,
				};
				curNodeList.value.push(timeObj);
			});
			nextTick(() => {
				initRules();
			});
		} else {
			props.handleType == 'edit' && addItem();
		}
	};

	//组装详情的form初始化表单
	const initFormList = obj => {
		let nowTime = new Date().getTime();
		let formList = deepClone(chargeRules);
		let effectState = obj.effectiveTime <= nowTime && nowTime <= obj.expiresTime ? '生效' : '失效';
		formList.forEach(filed => {
			if (filed.bindFieldName == 'effectiveTime') {
				filed.bindFieldVal = obj.effectiveTime;
			}
			if (filed.bindFieldName == 'expiresTime') {
				filed.bindFieldVal = obj.expiresTime;
			}
			if (filed.bindFieldName == 'effectState') {
				filed.bindFieldVal = effectState;
			}
		});
		return formList;
	};

	//新增
	const addItem = () => {
		let index = curNodeList.value.length + 1;
		let timeItem = {
			effectiveTime: new Date().getTime(),
			expiresTime: new Date('2100-12-31 23:59:59').getTime(),
			effectState: '生效',
		};
		let formList = initFormList(timeItem);
		let sourceObj = {
			name: '计费规则' + index,
			id: 'sm-drawer-demo-card-' + index,
			list: [
				{ name: '平值设置', startTime: '00:00', endTime: '23:59', price: '' },
				{ name: '峰值设置', startTime: '', endTime: '', price: '' },
				{ name: '谷值设置', startTime: '', endTime: '', price: '' },
			],
			formList: formList,
		};
		curNodeList.value.push(sourceObj);
		nextTick(() => {
			initRules();
		});
	};

	//提交
	const doConfirm = async () => {
		console.log(curNodeList);
		//所有表单的返回值(不包括table中的)
		let resArr = [];

		//校验每个表单
		for (let i = 0; i < formRef.value.length; i++) {
			let model = await formRef.value[i].validateForm();
			resArr.push(model);
		}
		if (resArr.includes(false)) return;

		//校验生效状态的唯一性
		let effectStateArr = resArr.map(item => item.effectState);
		let effectStateCount = countOccurrences(effectStateArr, '生效');
		if (effectStateCount > 1) {
			ElMessage({
				message: '只能存在一个生效信息!',
				type: 'warning',
			});
			return;
		}

		//校验单价是否全部填写
		for (let i = 0, len = curNodeList.value.length; i < len; i++) {
			let item = curNodeList.value[i];
			if (!item.list[0].price) {
				ElMessage({
					message: '请检查' + item.name + '的单价是否填写!',
					type: 'warning',
				});
				return;
			}
		}

		//入库
		let allocationVoList = [];
		curNodeList.value.forEach((item, index) => {
			let allocation = {
				effectiveTime: resArr[index].effectiveTime,
				expiresTime: resArr[index].expiresTime,
				projectCode: props.currentRow.projectCode,
			};
			allocation.averageStartTime = item.list[0].startTime;
			allocation.averageEndTime = item.list[0].endTime;
			allocation.averageUnitPrice = item.list[0].price;
			allocation.peakValueStartTime = item.list[1].startTime;
			allocation.peakValueEndTime = item.list[1].startTime;
			allocation.peakValueUnitPrice = item.list[1].startTime;
			allocation.valleyValueStartTime = item.list[2].startTime;
			allocation.valleyValueEndTime = item.list[2].startTime;
			allocation.valleyValueUnitPrice = item.list[2].startTime;
			allocationVoList.push(allocation);
		});

		let res = props.energyType == 'water' ? await chargeWaterSaveApi(allocationVoList) : await chargeEleSaveApi(allocationVoList);
		if (res.data.code !== 200) return;
		ElMessage({
			message: '提交成功',
			type: 'success',
		});
		isShowDrawer.value = false;
		emit('close', { isShow: false, isRefresh: true });
	};

	//校验重复性
	const countOccurrences = (arr, target) => {
		return arr.reduce((count, item) => (item === target ? count + 1 : count), 0);
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	//表单关联
	const selectChange = data => {
		let nowTime = new Date().getTime();
		if (data.filedName == 'effectiveTime' || data.filedName == 'expiresTime') {
			if (data.model.effectiveTime <= nowTime && nowTime <= data.model.expiresTime) {
				data.setFiledSource('effectState', '生效');
			} else {
				data.setFiledSource('effectState', '失效');
			}
		}
	};

	//table中的时间校验
	const timeChange = (data, row, filed) => {
		console.log(data);
		if (row.startTime && row.endTime) {
			let lock = validateTime(row.startTime, row.endTime);
			if (!lock) {
				ElMessage({
					message: '结束时间不能小于开始时间!',
					type: 'warning',
				});
				row.endTime = '';
			}
		}
	};

	//校验时间大小
	const validateTime = (startTime, endTime) => {
		const [startHour, startMinute] = startTime.split(':').map(Number); // 将 startTime 转换为小时和分钟
		const [endHour, endMinute] = endTime.split(':').map(Number); // 将 endTime 转换为小时和分钟
		const startTotalMinutes = startHour * 60 + startMinute; // 将 startTime 转换为总分钟数
		const endTotalMinutes = endHour * 60 + endMinute; // 将 endTime 转换为总分钟数
		return endTotalMinutes >= startTotalMinutes; // 判断 endTime 是否大于等于 startTime
	};

	//增加校验规则
	const initRules = () => {
		curNodeList.value.forEach((res, index) => {
			res.formList.forEach(item => {
				if (item.bindFieldName == 'effectiveTime' || item.bindFieldName == 'expiresTime') {
					item.rules = [{ validator: judgeDIffTime(formRef.value[index], 'effectiveTime', 'expiresTime', '生效时间', '失效时间'), trigger: ['change', 'blur'] }];
				}
			});
		});
	};

	//校验金钱
	const judgePrice = row => {
		let reg = /^\d+(\.\d{1,2})?$/;
		if (!reg.test(row.price) || row.price < 0) {
			row.price = '';
			ElMessage({
				message: '支持正数，最多小数点后两位!',
				type: 'warning',
			});
		}
	};

	// 将时间段转换为分钟数表示，并按开始时间排序
	const validateTimeRanges = timeRanges => {
		const sortedTimeRanges = timeRanges
			.map(range => {
				const [startHour, startMinute] = range.startTime.split(':').map(Number);
				const [endHour, endMinute] = range.endTime.split(':').map(Number);
				return {
					start: startHour * 60 + startMinute,
					end: endHour * 60 + endMinute,
				};
			})
			.sort((a, b) => a.start - b.start);

		// 校验时间段是否重复或不连续
		for (let i = 0; i < sortedTimeRanges.length - 1; i++) {
			const current = sortedTimeRanges[i];
			const next = sortedTimeRanges[i + 1];
			if (current.end > next.start) {
				ElMessage({
					message: '时间段重叠!',
					type: 'warning',
				});
				return false; // 时间段重叠，校验失败
			}
		}

		// 判断是否满足包含 24 小时
		if (sortedTimeRanges[0].start !== 0 || sortedTimeRanges[sortedTimeRanges.length - 1].end !== 24 * 60) {
			ElMessage({
				message: '不满足24小时!',
				type: 'warning',
			});
			return false;
		}

		return true; // 校验通过
	};

	// 示例数据
	const timeRanges = [
		{ startTime: '00:00', endTime: '10:00' },
		{ startTime: '10:00', endTime: '20:00' },
		{ startTime: '20:00', endTime: '24:00' },
	];

	// 执行校验
	const isValid = validateTimeRanges(timeRanges);
	console.log('时间段校验结果:', isValid);
</script>

<style lang="scss" scoped>
	.zs-table-page-main {
		::v-deep .el-input__inner {
			text-align: right;
		}
		::v-deep .el-input__prefix {
			display: none;
		}
		::v-deep .el-table__header {
			.cell {
				padding-right: 20px;
			}
		}
	}
	.el-time-spinner .el-time-spinner__wrapper {
		width: 50% !important;
	}
	.el-time-spinner .el-time-spinner__wrapper:nth-child(3) {
		display: none !important;
	}
	.add-btn {
		width: 100%;
	}
</style>
